<?php

namespace App\Repository;

use App\Exceptions\BusinessException;
use App\Common\Constant;
use App\Common\ResponseCode;
use App\Models\Base\Files;
use App\Models\Customer\Address;
use App\Models\Goods\AttributesValue;
use App\Models\Goods\FileBind;
use App\Models\Goods\Goods;
use App\Models\Goods\Products;
use App\Models\Role\Role;
use App\Models\Sales\OrderItems;
use App\Models\Sales\Orders;
use App\Models\User\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 订单数据仓储类
 *
 * @package App\Http\Repository
 * @author WangBin
 * @mail: <849850352@qq.com>
 */
class OrderRepository extends BaseRepository
{
    /**
     * 创建主订单
     *
     * @param array $orderData
     * @param int $orderId
     * @return int|mixed
     */
    public function create(array $orderData, int $orderId = 0)
    {
        $query = $orderId ? Orders::find($orderId) : new Orders();
        foreach ($orderData as $field => $value) {
            $query->{$field} = $value;
        }
        return $query->save() ? $query->order_id : 0;
    }

    /**
     * 创建订单明细
     *
     * @param int $orderId
     * @param array $goodsList
     */
    public function createItem(int $orderId, array $goodsList)
    {

        foreach ($goodsList as $goods) {
            $orderItem = new OrderItems();
            $orderItem->order_id = $orderId;
            $orderItem->product_id = $goods['product_id'];
            $orderItem->goods_id = $goods['goods_id'];
            $orderItem->name = $goods['name'];
            $orderItem->goods_bn = $goods['goods_bn'];
            $orderItem->product_bn = $goods['goods_bn'];
            $orderItem->unit = $goods['unit'];
            $orderItem->specs = $goods['specs'];
            $orderItem->image_url = $goods['image_url'];
            $orderItem->is_gift = $goods['is_gift'];
            $orderItem->price = $goods['price'];
            $orderItem->qty_ordered = $goods['qty_ordered'];
            $orderItem->total_amount = $goods['total_amount'];
            $orderItem->save();
        }
    }

    /**
     * 订单列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getList(array $filter = [])
    {
        $query = Orders::query()->orderByDesc('created_at');
        if(!empty($filter['customer_id'])) {
            $query->whereIn('customer_id', $filter['customer_id']);
        }
        if(!empty($filter['start_date'])) {
            $query->where('created_at', '>=', $filter['start_date']);
        }
        if(!empty($filter['end_date'])) {
            $query->where('end_at', '<=', $filter['end_date']);
        }
        if(!empty($filter['status'])) {
            $query->whereIn('status', $filter['status']);
        }
        if(!empty($filter['order_bn'])) {
            $query->where('order_bn', $filter['order_bn']);
        }
        if(!empty($filter['mobile'])) {
            $query->where('mobile', $filter['mobile']);
        }
        if(!empty($filter['region'])) {
            $query->where('address', 'like', '%' . $filter['region'] . '%');
        }
        if(!empty($filter['order_from'])) {
            $query->where('order_from',$filter['order_from']);
        }
        if(isset($filter['is_comment'])) {
            $query->where('is_comment', $filter['is_comment']);
        }
        return $query;
    }

    /**
     * H5 订单可操作按钮
     *
     * @param string $status
     * @return array
     */
    public function getCanActions(string $status)
    {
        $actions = [];
        switch ($status)
        {
            case Constant::ORDER_STATUS_CREATED:
            case Constant::ORDER_STATUS_WAIT_PAY:
                $actions = ['cancel', 'pay', 'delete'];
                break;
            case Constant::ORDER_STATUS_PAYED:
                $actions[] = 'cancel';
                break;
            case Constant::ORDER_STATUS_CANCEL:
            case Constant::ORDER_STATUS_FINISHED:
            $actions[] = 'delete';
                break;
            case Constant::ORDER_STATUS_DELIVERY_PART:
            case Constant::ORDER_STATUS_DELIVERY_ALL:
                $actions = ['express', 'confirm'];
                break;
        }
        return $actions;
    }

    /**
     * 中台订单可操作按钮
     * 包含：查看、编辑、删除、发货、取消 操作
     * @param string $status
     * @return array
     */
    public function getAdminCanActions(string $status)
    {
        $actions = ['view'];
        switch ($status)
        {
            case Constant::ORDER_STATUS_CREATED:
            case Constant::ORDER_STATUS_WAIT_PAY:
                $actions = ['cancel', 'delete'];
                break;
            case Constant::ORDER_STATUS_PAYED:
                $actions[] = 'delivery';
                break;
            case Constant::ORDER_STATUS_CANCEL:
                $actions[] = 'delete';
                break;
        }
        return $actions;
    }

    /**
     * 获取订单明细
     *
     * @param int $orderId
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getItems(int $orderId)
    {
        return OrderItems::query()->where('order_id', $orderId)->get();
    }

    /**
     * 更新订单
     *
     * @param array $data
     * @param int $orderId
     * @return int
     */
    public function update(array $data, int $orderId)
    {
        $query = Orders::find($orderId);
        foreach ($data as $field => $value) {
            $query->{$field} = $value;
        }
        return $query->save() ? $query->order_id : 0;
    }

    /**
     * 获取订单
     *
     * @param int $orderId
     * @param bool $lock
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getById(int $orderId, bool $lock = false)
    {
        $query = Orders::query()->where('order_id', $orderId);
        if($lock) {
            $query->lockForUpdate();
        }
        return $query->first();
    }

    /**
     * 获取订单详情信息
     *
     * @param int $orderId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getOrderInfo(int $orderId)
    {
        $order = $this->getById($orderId);
        // 转化数据
        $order->status_name = Constant::ORDER_STATUS_MAP[$order->status];
        $order->pay_status_name = Constant::PAY_STATUS_MAP[$order->pay_status];
        $order->pay_method_name = Constant::PAY_METHOD_MAP[$order->pay_method];
        $order->order_from = Constant::ORDER_FROM_MAP[$order->order_from];
        $order->buy_mode = Constant::ORDER_BUY_MODE_MAP[$order->buy_mode];
        $order->delivery_type_name = Constant::DELIVERY_TYPE_LIST[$order->delivery_type];
        // 订单明细
        $order->items = OrderItemRepository::getInstance()->getByOrderId($orderId);
        // 发货单
        $order->delivery = DeliveryRepository::getInstance()->getByOrderId($orderId);
        // 订单状态
        $order->status_name = Constant::ORDER_STATUS_MAP[$order->status];
        // 订单可操作相
        $order->actions = $this->getCanActions($order->status);
        return $order;
    }
}
